templatePath = 'template-path/'
handleCmis401Error= (errorResponse)->
  if errorResponse.status == 401
    if window.location.href.indexOf('localhost') != -1
      alert('TOKEN ERROR UPDATE YOUR TOKEN')
    else
      if window.location.href.indexOf('file') != -1 && CmisService.device == 'platform-pad'
        $location.path('/app/logout', false)
      else if window.UCX_relogin && typeof window.UCX_relogin == 'function'
        window.UCX_relogin();
      else
        window.location.href = '/site/re-login?url='+window.location.href
    true
  else
    false
angular.module('UCX.Cmis')
.provider "CmisService", ()->
  service = {
    $get: ()->
      {
        setConfig: (
          url,
          token,
          path = '/',
          baseUrl = '/',
          isDrmRoom = 'false'
          messageToMember = ''
          showMembers = 'true'
          roomLink = ''
          previewDid = ''
          allowExtension = ''
          repository = ''
          membershipType = ''
          allowDownload = 'true'
          filePickerModal = ''
          device = ''
          pluginVersion = ''
          fromFillAndSign=false
          cwebToolsApi = ''
          pluginUi = ''
          fileType = ''
          fileSelectMode = ''
        )->
          session = cmis.createSession(url)
          session.setToken(token)
          session.setGlobalHandlers(handleCmis401Error)
          this.session = session
          this.path = path
          this.token = token
          this.email = decodeURIComponent(token).split(',')[1]
          this.baseUrl = baseUrl
          this.isDrmRoom = if isDrmRoom != 'false' && isDrmRoom != '0' then true else false
          this.messageToMember = messageToMember
          this.showMembers = if showMembers != 'false' && showMembers != '0' then true else false
          this.roomLink = roomLink
          this.previewDid = previewDid
          this.allowExtension = if allowExtension == '' then [] else allowExtension.split(',')
          this.repository = repository
          this.device=device
          this.filePickerModal = filePickerModal
          this.device = device
          this.pluginVersion = pluginVersion
          this.fromFillAndSign = fromFillAndSign
          this.membershipType = membershipType
          this.cwebToolsApi = cwebToolsApi
          this.allowDownload = if allowDownload != 'false' && allowDownload != '0' then true else false
          this.pluginUi = pluginUi
          this.fileType = fileType
          this.fileSelectMode = fileSelectMode
          console.log this
      }
  }
  service

.service "Loading", ($uibModal, $timeout)->
  modalInstance = null
  timerPromise = null
  this.open = (content = "uploading")->
    modalInstance = $uibModal.open {
      animation: true,
      templateUrl: templatePath + "loading.html",
      size: 'sm',
      backdrop: false,
      controller: 'LoadingController',
      windowClass:'modal-opacity'
      resolve: {
        content: ()->
          return content
      }
    }
    timerPromise = $timeout ()->
      modalInstance.dismiss('cancel')
    ,
      20000
  this.close = ()->
    $timeout.cancel(timerPromise)
    modalInstance.dismiss('cancel')

  this

.factory "Utils", ($uibModal, toastr, localStorageService, CmisService, toastrConfig, $translate, $timeout, $location)->
  timer = {}
  {
  rootFolder:null,
  currentFolder:{},
  searchType:''
  loadingSearchResult:false
  currentUrl:''
  isUploadNewVersioning :false
  formatAcl:(acl)->
#   accept {"inherited":[{"principalId":"everyone","permissions":["smx:none"]},{"principalId":"ww002@mailinator.com","permissions":["cmis:all"]}]}
#   return [{"principal":{"principalId":"ww002@mailinator.com"},"permissions":["cmis:all"],"isDirect":true}]
    resultAcls = []
    if acl.inherited
      for inheritedAcl in acl.inherited
        result = {
          principal:{'principalId':inheritedAcl.principalId}
          permissions:inheritedAcl.permissions
          isDirect:false
        }
        resultAcls.push(result)

    if acl.direct
      for directAcl in acl.direct
        result = {
          principal:{'principalId':directAcl.principalId}
          permissions:directAcl.permissions
          isDirect:true
        }
        resultAcls.push(result)
    resultAcls

  connectCmis : ()->
    baseUrl = 'https://cloud-demo.connectedpdf.com/'
    url = 'https://cloud-demo.connectedpdf.com/cmis/browser'

    calculatePath = (userEmail) ->
      lowerEmail = userEmail.toLowerCase()
      cleanId = (lowerEmail + 'aaaa').replace(/[^a-zA-Z]/g, '')
      result = cleanId.substring(0, 2) + '/' + cleanId.substring(2, 4) + '/' + lowerEmail
      path = '/User_Homes/' + result + '/Reading'
      path
    if window.FX
      token = localStorage.getItem('share_plugin_token') || this.getCookie('currentToken')
      baseUrl = localStorage.getItem('share_plugin_baseUrl')
      url = localStorage.getItem('share_plugin_url')
      if window.phantomOnlineGlobalConfig
        baseUrl = phantomOnlineGlobalConfig.apiUrl
        url = baseUrl + 'cmis/browser'
      token = decodeURIComponent(token)
      email = token.split(',')[1]
      path = calculatePath(email)
    else
      console.log('====Utils====')
      console.log(this)
      token = this.getCookie('currentToken') || CmisService.token
      email = this.getCookie('currentEmail') || CmisService.email
      path = calculatePath(email)
    CmisService.setConfig url, token, path, baseUrl, false, '', false, '', '', '', 'fxcld', '', '', '', 'phantom-online', '', false


  setContentStream:(params,successCallback,errorCallback) ->
    docId = params.id;
    connectCmis();
    CmisService.session.getContentStream(docId, true).ok (data)->
      console.log('filedata.....',data);

      CmisService.session.setContentStream(docId, data).ok (data2)->
        console.log('setContentStreamfiledata222222222.....',data2);
        successCallback && successCallback()
      .notOk (error)->
        if Utils.handleCmis401Error(error)
          return
        errorCallback && errorCallback(error)
    .notOk (error)->
      if Utils.handleCmis401Error(error)
        return
      errorCallback && errorCallback(error)

  urlParaToObj: (urlPara, needEncode) ->
    obj = {}
    if urlPara.indexOf('%')>-1
      urlPara = decodeURIComponent(urlPara)
    if urlPara.indexOf('&') != -1
      arr = urlPara.split('&')
      k = 0
      len1 = arr.length
      while k < len1
        i = arr[k]
        if needEncode
          obj[i.split('=')[0]] = encodeURIComponent(i.split('=')[1])
        else
          obj[i.split('=')[0]] = i.split('=')[1]
        k++
    else
      if needEncode
        obj[urlPara.split('=')[0]] = encodeURIComponent(i.split('=')[1])
      else
        obj[urlPara.split('=')[0]] = urlPara.split('=')[1]
    obj
  getArgsFromUrl:(url)->
    if (!url)
      url = location.href
    index = url.indexOf('?')
    if (index == -1)

    else
      urlParas = url.slice(index + 1)
      result = urlParaToObj(urlParas)
      console.log(result)
    return result
  sendGaEvent: (category, action, label) ->
    if window.ga and typeof window.ga == 'function'
      if CmisService.device=='foxitReader'
        ga('file_picker.send', {
          hitType: 'event',
          eventCategory: category,
          eventAction: action,
          eventLabel: label,
          eventValue: 0
        })
        ga('send',{
          hitType: 'event'
          eventCategory: category
          eventAction: action
          eventLabel: label
          eventValue: 0
        })
      else
        ga('send',{
          hitType: 'event'
          eventCategory: category
          eventAction: action
          eventLabel: label
          eventValue: 0
        })
  containIllegalChar:(str)->
    illegalCharacters=['/', '\\', ':', '"', '*', '?', '<', '>', '|', '%']
    for char in illegalCharacters
      if str.indexOf(char)>-1
        return true
    return false
  getOsName:()->
    sUserAgent = navigator.userAgent
    isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows")
    isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel")
    isUnix = (navigator.platform == "X11") && !isWin && !isMac
    isLinux = (String(navigator.platform).indexOf("Linux") > -1)
    if(isWin)
      OS = 'windows'
    if isMac
      OS = 'mac'
    if isUnix
      OS = 'unix'
    if isLinux
      OS = 'linux'
    return OS
  isIEorEdge:()->
    IERESULT = false
    userAgent = navigator.userAgent
    isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1
    if (navigator.appVersion.indexOf("MSIE 10") != -1)
      IE10=true
    else
      IE10=false

    if (userAgent.indexOf("Trident") != -1 && userAgent.indexOf("rv:11") != -1)
      IE11=true
    else
      IE11=false

    if (userAgent.indexOf('Edge')>-1)
      IEEdge=true
    else
      IEEdge=false
    if isIE || IE11 || IE10 || IEEdge
      IERESULT = true

    return IERESULT
  isSafari:()->
    return navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") == -1
  browserIsIE:()->
    if (navigator.appVersion.indexOf("MSIE 10") != -1)
#        window.alert('This is IE 10')
      IE10=true
    else
      IE10=false
    #     detect ie11
    UAString = navigator.userAgent
    if (UAString.indexOf("Trident") != -1 && UAString.indexOf("rv:11") != -1)
#        window.alert('This is IE 11');
      IE11=true
    else
      IE11=false
    if IE11 || IE10
      IE = true
    else
      IE = false
    return IE

  showFilenameTooltip:(document)->
#    console.log document.id
    id=document.id
#    Todo 用现成的  browserIsIE方法
    if (navigator.appVersion.indexOf("MSIE 10") != -1)
#        window.alert('This is IE 10')
      IE10=true
    else
      IE10=false
    #     detect ie11
    UAString = navigator.userAgent

    if (UAString.indexOf('Edge')>-1)
      IEEdge=true
    else
      IEEdge=false
    if (UAString.indexOf("Trident") != -1 && UAString.indexOf("rv:11") != -1)
#        window.alert('This is IE 11');
      IE11=true
    else
      IE11=false
    if IE11 || IE10 || IEEdge
      IE = true
    else
      IE = false
    init=()->
      onloadToolHint=$('[data-id="'+id+'"]').find('.tooltip-hint').width()
      if onloadToolHint && parseInt(onloadToolHint)>0
        if IE
          $('div[data-id="'+id+'"]').find('.tooltip-hint-parent').find('.long-words-handle').css('width','auto')
          $('tr[data-id="'+id+'"]').find('.tooltip-hint-parent').find('.long-words-handle').css('width','auto')
        if $('div[data-id="'+id+'"]').length && $('div[data-id="'+id+'"]').find('.tooltip-hint-parent').width()<$('div[data-id="'+id+'"]').find('.tooltip-hint').width() || $('tr[data-id="'+id+'"]').length && $('tr[data-id="'+id+'"]').find('.tooltip-hint-parent').width()-12<=$('tr[data-id="'+id+'"]').find('.tooltip-hint').width()
          if $('[data-id="'+id+'"]').find('.tooltip-hint-parent').hasClass('not-show-tooltip')
            $('[data-id="'+id+'"]').find('.tooltip-hint-parent').removeClass('not-show-tooltip')
        else
#          console.log 'add'
#          console.log $('[data-id="'+id+'"]').find('.tooltip-hint-parent')
#          console.log $('[data-id="'+id+'"]').find('.tooltip-hint-parent').width()
#          console.log $('[data-id="'+id+'"]').find('.tooltip-hint').width()
          $('[data-id="'+id+'"]').find('.tooltip-hint-parent').addClass('not-show-tooltip')
        if IE
          $('div[data-id="'+id+'"]').find('.tooltip-hint-parent').find('.long-words-handle').css('width','100%')
          $('tr[data-id="'+id+'"]').find('.tooltip-hint-parent').find('.long-words-handle').css('width','100%')
      else
        $timeout ()->
          init()
        , 1000
    init()
  sqlContainIllegalChar:(str)->
    illegalCharacters=['/', '\\', ':', '"', '*', '?', '<', '>', '|', '%', "'"]
    for char in illegalCharacters
      if str.indexOf(char)>-1
        return true
    return false
  translateErrorMsg : (responseJsonDate, args)->
    if responseJsonDate.errorCode
      $translate(responseJsonDate.errorCode, args).then(
        (text)->
          toastr.warning(text)
      ,
        ()->
          toastr.warning(responseJsonDate.message)
      )
    else
      toastr.warning(responseJsonDate.message)
  getFileExt: (fileName)->
    index = fileName.lastIndexOf('.')
    if index != -1
      ext = fileName.substr(index+1).toLowerCase()
    else
      ext = ''
    ext
  isImg: (document)->
    mimeType = if document.type then document.type else if document.contentStreamMimeType then document.contentStreamMimeType else ''
    mimeType.split('/')[0] == 'image'
  isText: (document)->
    mimeType = if document.type then document.type else if document.contentStreamMimeType then document.contentStreamMimeType else ''
    mimeType.split('/')[0] == 'text'
  isAllowExtension: (document)->
    ext = this.getFileExt(document.name)
    CmisService.allowExtension.length ==0 || CmisService.allowExtension.indexOf(ext) > -1
  getMimeTypeFromExt: (fileName)->
    ext = this.getFileExt(fileName)
    mimeTypeMap={
      'pdf':'application/pdf'
      'doc':'application/msword'
      'ppt':'application/vnd.ms-powerpoint'
      'xls':'application/vnd.ms-excel'
      'wri':'application/x-mswrite'
      'rtf':'application/rtf'
      'docx':'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      'pptx':'application/vnd.openxmlformats-officedocument.presentationml.presentation'
      'xlsx':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      'txt':'text/plain'
      'bmp':'image/bmp'
      'png':'image/png'
      'gif':'image/gif'
      'jpeg':'image/jpeg'
      'jeg':'image/jpeg'
      'tiff':'image/tiff'
    }
    mimeType = mimeTypeMap[ext]||''
    return mimeType
  canPreview: (document)->
    #  https://jira.foxitsoftware.cn/browse/CBASE-362 support type is here
    #  https://jira.foxitsoftware.cn/browse/CVAS-560  具体预览的 情况
    allowPreviewTypes = [
      'application/pdf'
      'application/msword'
      'application/vnd.ms-powerpoint'
      'application/vnd.ms-excel'
      'application/x-mswrite'
      'application/rtf'
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      'application/vnd.openxmlformats-officedocument.presentationml.presentation'
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      'text/plain'
      'image/bmp'
      'image/png'
      'image/gif'
      'image/jpeg'
      'image/tiff'
    ]
    mimeType = if document.contentStreamMimeType then document.contentStreamMimeType else ''
    allowPreviewTypes.indexOf(mimeType) > -1
  localOpenDocumentPreview: (document)->
    allowPreviewTypes = ['application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.text-template', 'application/vnd.oasis.opendocument.presentation-template', 'application/vnd.oasis.opendocument.presentation', 'application/vnd.oasis.opendocument.spreadsheet', 'application/vnd.oasis.opendocument.spreadsheet-template']
    mimeType = if document.contentStreamMimeType then document.contentStreamMimeType else ''
    allowPreviewTypes.indexOf(mimeType) > -1
  isOther: (document)->
    !this.isImg(document) && !this.isText(document) && !this.isPdf(document)
  confirm: (confirmContent,confirmTitle,confirmBtnText,cancelBtnText, callback)->
    modalInstance = $uibModal.open {
      templateUrl: templatePath + 'confirm.html'
      controller: 'ConfirmController'
      windowClass:'modal-opacity'
      resolve: {
        content: ()->
          confirmContent
        title: ()->
          confirmTitle
        confirmBtnText: ()->
          confirmBtnText
        cancelBtnText: ()->
          cancelBtnText
      }
    }
    modalInstance.result.then ()->
      callback()
    false
  isValidEmail: (email)->
    emailPattern=/^[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/
    isValidEmail=emailPattern.test(email);
    return isValidEmail
  success: (content)->
    toastr.success content.toString()
  warning: (content)->
    toastr.warning content.toString()

  info: (content)->
    toastr.info content.toString()
  clearToastr: ()->
    toastr.clear()
  getSort: ()->
    if localStorageService.isSupported
      folderOrderBy = localStorageService.get "folder-order-by"
      folderOrderBy = if folderOrderBy then folderOrderBy else '-contentStreamLength'
    else
      folderOrderBy = '-contentStreamLength'
    folderOrderBy
  getFileSort: ()->
    if localStorageService.isSupported
      fileSort = localStorageService.get "file-order-by"
      #      console.log fileSort
      if fileSort == null
        fileSort=true
#      console.log fileSort
    else
      fileSort = true
    fileSort
  getLanguage : ()->
    if localStorageService.isSupported
      language = localStorageService.get "language"
      language = if language then language else 'US'
    else
      language = 'US'
    language
  handleTokenError : (error)->
    if error && error.message == 'TOKEN_ERROR'
      if window.location.href.indexOf('localhost') != -1
        alert('TOKEN ERROR UPDATE YOUR TOKEN')
      else
        if window.location.href.indexOf('file') != -1 && CmisService.device == 'platform-pad'
          $location.path('/app/logout', false)
        else if window.UCX_relogin && typeof window.UCX_relogin == 'function'
          window.UCX_relogin();
        else
          window.location.href = '/site/re-login?url='+window.location.href

  handleCmis401Error: (errorResponse)->
    handleCmis401Error(errorResponse)

  rebound : (key, callback, time)->
    if !timer
      timer={}
    if typeof timer[key] != 'undefined'
      clearTimeout(timer[key])
    timer[key] = setTimeout( ()->
      callback()
    , time)
#  wait for dom load then callback
  waitForDomReady: (elemSelector,successfulCallback,errCallback,interval,totalWaitSec)->
    _this = this
    if !interval
      interval = 200
    if !totalWaitSec
      totalWaitSec = 10000
    count = 0
    timer = null
    if $(elemSelector).length==0
      timer = setTimeout(()->
        count++
        if count>=totalWaitSec/interval
          if errCallback
            errCallback()
          console.log ' $(elemSelector) does not exist '
          return false
        else
          _this.waitForDomReady(elemSelector,successfulCallback,errCallback,interval,totalWaitSec)
      ,interval)
    else
      if successfulCallback
        successfulCallback()
  calculateDaysBetween: (date1,date2)->
   # 2017-02-12    2014-04-30   return 1019
    date1_arr = date1.split('-')
    date1_year = date1_arr[0]
    date1_month = parseInt(date1_arr[1],10)-1
    date1_day = parseInt(date1_arr[2],10)

    date2_arr = date2.split('-')
    date2_year = date2_arr[0]
    date2_month = parseInt(date2_arr[1],10)-1
    date2_day = parseInt(date2_arr[2],10)

    days = parseInt((new Date(date2_year,date2_month,date2_day)-new Date(date1_year,date1_month,date1_day))/1000/60/60/24)
    console.log('日期相差',days)
    return days
  formatDate: (dateType)->
#   dateType can be new Date()  new Date(year,month,date)
#   date type to  2014-03-03 or 2014-1-1
    date = dateType.getDate()
    month = parseInt(dateType.getMonth())+1
    year = dateType.getFullYear()
    return year+'-'+month+'-'+date
  getCookie: (key)->
    reg=new RegExp("(^| )"+key+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
      return unescape(arr[2]);
    else
      return '';

  # READ ONLY FOLDERS: cannot rename, cannot delete, cannot move to other folders, cannot move other thinks to these folders, cannot upload file cannot create folder into these folders...
  readOnlyFolders: ()->
    return ["/Webforms/", "/Connectedpdf/"];
  }
.factory "UploadQueue", (CmisService, $uibModal, ModelService, $rootScope, $translate, $timeout, Utils)->
  CmisServiceSession = CmisService.session
  {
    barIsOpen:true
    uploading: false
    queueFiles:[],
    hasErrMsg:false
    isBarOpen:()->
      @barIsOpen
    isUploading:()->
      @uploading
    hasErrMsgFunc:()->
      @hasErrMsg
    add: (file, targetId, options, versionType, successCallback)->
      queueFile = {
        file: file
        targetId: targetId
        options: options
        versionType: 'major'
        isUploaded: false
        status: $translate.instant('waiting')
        statusCode:1
        loaded: 0
        percent: 0
      }
      @queueFiles.unshift(queueFile)
      @showProgressBar()
      @uploadNext(successCallback)
    getNextFile: ()->
      return file for file in @queueFiles when !file.isUploaded

    uploadNext: (successCallback)->
      _this = this
      file = @getNextFile()
      if file
        file.statusCode=2
      if !file
        @uploading = false
        if @hasErrMsg
          @barIsOpen = true
        else
          @barIsOpen = false
#        @barIsOpen = false
#        $('#progress-bar-modal').hide('slow')
#        $('#progress-bar').hide('slow')
#        $rootScope.$apply()
        return
      if @uploading
        @barIsOpen = true
#        $('#progress-bar').show('slow')
        return
      @uploading = true
      @barIsOpen = true
#      $('#progress-bar').show('slow')

      okFunction = (object)->
        # refresh list by js not by server
        newFile = ModelService.createDocument object
        tempFolder = ModelService.getObjectById(file.targetId)
        tempFolder.children = [] if !tempFolder.children
        tempFolder.children.push(newFile)
        Utils.sendGaEvent "Document", "Upload", newFile.id
        newFile.createActivity "upload-document", {document_name: newFile.name, document_id: newFile.id}
        file.isUploaded = true
        file.status = $translate.instant('success')
        file.statusCode = 0
        _this.uploading = false
        _this.uploadNext(successCallback)
        if successCallback
          successCallback()

      notokFunction = (r)->
        if Utils.handleCmis401Error(r)
          return
        if r && r.text
          try
            data = JSON.parse(r.text)
          catch e

          file.isError = true
          _this.hasErrMsg = true
          file.status = $translate.instant('Error')
          file.statusCode = 3
          file.percent = 0
          file.loaded = 0
          if data
            file.errorMsg = $translate.instant(data.errorCode,{name:file.file.name})
          else
            file.errorMsg = $translate.instant('Error',{name:file.file.name})
          file.isUploaded = true
          _this.uploading = false
          _this.barIsOpen = true
          _this.uploadNext(successCallback)
          if successCallback
            successCallback()


      progressFunction = (e)->
        file.loaded = e.loaded
        file.total = e.total
        file.percent = Math.floor(e.percent)
        file.status = $translate.instant('uploading')
        if successCallback
          successCallback()

      if CmisService.isAndroid
        filePath = encodeURI(file.file.filepath)
        # for android
        console.log 'file://' + filePath
        window.resolveLocalFileSystemURL 'file://' + filePath, ((fileEntry) ->
          console.log fileEntry
          fileEntry.file (localfile) ->
            reader = undefined
            reader = new FileReader

            reader.onloadend = (fileReadResult) ->
              data = undefined
              data = new Uint8Array(fileReadResult.target.result)
              fileBolbData = new Blob([ data ], type: file.file.type)
              _this.currentUploadFile = CmisService.session.createDocument(file.targetId, fileBolbData, file.options, file.file.type, file.versionType)
              _this.currentUploadFile.ok(okFunction).notOk(notokFunction).getRequest().on 'progress', progressFunction

            reader.readAsArrayBuffer localfile
        ), (error) ->
          console.log error
      else
        reader = new FileReader
        mimeType = Utils.getMimeTypeFromExt(file.file.name)
        reader.addEventListener("loadend", (fileReadResult)->
          data = new Uint8Array(fileReadResult.target.result)
          fileBlobData = new Blob([ data ], type: mimeType||file.file.type)
          _this.currentUploadFile = CmisService.session.createDocument(file.targetId, fileBlobData, file.options, mimeType||file.file.type, file.versionType)
          _this.currentUploadFile.ok(okFunction).notOk(notokFunction).getRequest().on 'progress', progressFunction
        )
        reader.readAsArrayBuffer(file.file)


#      CmisService.session.createDocument(
#        file.targetId,
#        file.file,
#        file.options,
#        file.file.type,
#        file.versionType
#      ).ok okFunction
#      .notOk notokFunction
#      .getRequest().on('progress',progressFunction
#      )

    showProgressBar: ()->
      _this = this
      $('#progress-bar-modal').show('slow')

#      if(!@modal)
#        @modal = $uibModal.open ({
#          animation: true,
#          backdrop:false,
#          windowTopClass:'progress-bar-window',
#          templateUrl: templatePath + "progress-bar.html",
#          controller: "createProgressBarModal",
#          resolve:{
#            queueFiles:()->
#              _this.queueFiles
#            rootScope:()->
#              $rootScope
#          }
#        })
#      else
#        $('#progress-bar').show('slow')
  }
.factory "ApiService", (CmisService, $translate, $timeout,Utils,$http,ModelService, localStorageService)->
  CmisServiceSession = CmisService.session
  {
    uploadUrlToCmis:(fileUrl,fileName,successfulCallback,errCallback)->
      url =  CmisService.baseUrl+'api/v3/document/cmis?access-token='+CmisService.token
#      postData={
#        "file_url":fileUrl
#        "name":fileName
#        "fake":"true"
#      }
      postData = new FormData()
      postData.append("file_url",fileUrl)
      postData.append("name",fileName)
      postData.append("fake", true)
      postData.append("auto_rename", true)
      #      postData = new FormData()
      #      postData.append("object_id", file.id)
      #      postData.append("share_info", JSON.stringify(shareInfo))
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        contentType:false
        processData: false
        success: (data)->
          if data
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              successfulCallback(data)
          else
            console.log(data)
            if data && data.code
              errCallback && errCallback(data)
            if data && data.message != 'TOKEN_ERROR'
              Utils.warning(data.message)
        error: (err)->
          console.log(err)
          if err && err.code
            errCallback && errCallback(err)
      })

    setDownloadPerm:(shareCode,disableDownload,successfulCallback,errCallback)->
      if window.FX || window.PhantomOnline
        Utils.connectCmis()
      url =  CmisService.baseUrl+'api/share/download-settings?access-token='+CmisService.token
      postData={
        "share_code": shareCode
        "can_download":if disableDownload then false else true
      }
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        success: (data)->
          if data.data && data.ret == 0
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              successfulCallback(data)
          else
            console.log(data)
            if data && errCallback
              errCallback(data)
#            if data && (data.message != 'TOKEN_ERROR' || data.msg != 'TOKEN_ERROR')
#              Utils.warning(data.msg || data.message)
        error: (err)->
          if err && errCallback
            errCallback(err)

          console.log(err)
      })

    setSharedInfo:(file,shareInfo,message,disableDownload,successfulCallback,errCallback)->
      # shareInfo  [{'everyone': 'cmis:write'},{'131122@mailinator.com': 'cmis:write'}]
      if window.FX || window.PhantomOnline
        Utils.connectCmis()
      url =  CmisService.baseUrl+'api/share/share?access-token='+CmisService.token
      if(!message)
        message=''
      postData={
        "object_id":file.id
        "share_info":JSON.stringify(shareInfo)
        "message":message
        "can_download":if disableDownload then false else true
      }

#      postData = new FormData()
#      postData.append("object_id", file.id)
#      postData.append("share_info", JSON.stringify(shareInfo))
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        success: (data)->
          if data.data && data.ret == 0
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              successfulCallback(data)
          else
            console.log(data)
            if data && errCallback
              errCallback(data)
            if data && (data.message != 'TOKEN_ERROR' || data.msg != 'TOKEN_ERROR')
              Utils.warning(data.msg || data.message)
        error: (err)->
          if err && errCallback
            errCallback(err)

          console.log(err)
      })
    getSharedInfo:(file,force,successfulCallback,errCallback)->
#      sharedLink "http://docker.mydo.cx/Xjo"  Xjo
#      shareCode =file.sharedLink.split('/').pop()
      url =  CmisService.baseUrl+'api/share/share?access-token='+CmisService.token

      currentUserId = CmisService.email
      if(window.PhantomOnline && !currentUserId)
        currentUserId = localStorage.getItem('currentEmail')
      userInfo={}
      tempUserInfo={}
      shareInfo=[]
      userInfo[currentUserId]="cmis:all"
      shareInfo.push(userInfo)
      #add other direct user
      for item,key in file.aces
        if item.isDirect == true && item.userId!=file.createdBy.id
          tempUserInfo[item.userId] = item.permission
          shareInfo.push(tempUserInfo)
      console.log(shareInfo);
      postData={
        "object_id":file.id
        "share_info":JSON.stringify(shareInfo)
      }
      console.log('@@@@@@@@@')
      console.log(postData)
#      postData = new FormData()
#      postData.append("object_id", file.id)
#      postData.append("share_info", shareInfo)
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        success: (data)->
          console.log('data')
          console.log(data)
          if data.data && data.ret == 0
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              successfulCallback(data.data.share)
          else
            console.log(data)
            if data && data.message != 'TOKEN_ERROR'
              Utils.warning(data.message)
        error: (err)->
          console.log(err)
      })

    getAclByFileId:(fileId,SuccessCallback,ErrorCallback)->
      CmisService.session.getACL(fileId, true).ok (data)->
        _this.aces = (new Ace ace for ace in data.aces when ace.principal.principalId != 'everyone' && ace.permissions[0] != "cmis:all")
        SuccessCallback && SuccessCallback()
      .notOk (error)->
        if Utils.handleCmis401Error(error)
          return
        ErrorCallback && ErrorCallback(error)
    setAcl:(fileId,addedAcl,deletedAcl)->



    getSharedFileLink: (file,force,successfulCallback,errCallback)->
      if force || !file.sharedLink
        url =  CmisService.baseUrl+'api/share/public?access-token='+CmisService.token
        #    url =  'https://cloud-vagrant.connectedpdf.com'+'/api/share/public'
        postData = new FormData()
        postData.append("doc_id", file.id)
        postData.append("fake", true)
        $.ajax({
          type: 'POST'
          url:url,
          beforeSend: (request)->
            request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
          data: postData
          contentType:false
          processData: false
          success: (data)->
            if data.data && data.ret == 0
              if successfulCallback
  #              successfulCallback(sharedFileInfo)
                successfulCallback(data.data.short_url)
            else
              console.log(data)
              if data && data.message != 'TOKEN_ERROR'
                Utils.warning(data.message)
          error: (err)->
            console.log(err)
        })
      else
        if successfulCallback
#          successfulCallback(sharedFileInfo)
          successfulCallback(file.sharedLink)
    closeSharedLink:(code,successfulCallback,errCallback)->
      url =  CmisService.baseUrl+'api/share/delete_public?access-token='+CmisService.token
      #    url =  'https://cloud-vagrant.connectedpdf.com'+'/api/share/public'
#      postData = new FormData()
#      postData.append("code", code)
      postData={
        code:code
      }
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        contentType:'application/x-www-form-urlencoded'
#        processData: false
        success: (data)->
          if data.data && data.data==1
            if successfulCallback
              successfulCallback(data)
          else
            console.log(data)
        error: (err)->
          console.log(err)
      })
    getRecentViewedFile:(query,successfulCallback)->
#      https://cloud-docker.connectedpdf.com/api/document/recent-files?access-token=58aa5d7de4b0b7dd7200ad18%2Cww002%40mailinator.com
      url =  CmisService.baseUrl+'api/document/recent-files?access-token='+encodeURIComponent(CmisService.token)
#          url =  'https://cloud-vagrant.connectedpdf.com'+'/api/share/public'
#            postData = new FormData()
      #      postData.append("code", code)
      postData={
        days:query
      }
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        success: (data)->
#          return arr of object ids
          if data && successfulCallback
              successfulCallback(data)
          else
            console.log(data)
        error: (err)->
          console.log(err)
      })
    cmisSQL:(params,successfulCallback)->
#      post https://cloud-docker.connectedpdf.com/cmis/browser/fxcld?succinct=true&token=58b38d0ee4b0e5b2508af0e8%2Cww002%40mailinator.com&cmisaction=query&statement=SELECT%20*%20from%20cmis%3Adocument%20WHERE%20IN_TREE(%27cc76b247-9834-4e4c-972a-668452bdb6c5%27)&searchAllVersions=false
      if !params
        return
#      deffer = $.Deferred()
      url = CmisService.baseUrl+'cmis/browser/fxcld?'
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data:params
        success: (data)->
          #  生成 数组并返回
          if !data
            console.log(data)
        error: (err)->
          console.log(err)
      })
  }

##
#
#   all $http response-success or response-error handle token error
#
##
.factory('myInterceptor', ($log,$injector)->
#  $log.debug('$log is here to show you that this is a regular factory with injection')
  myInterceptor = {
    response:(data)->
      if data && data.data && data.data.message == 'TOKEN_ERROR'
        Utils = $injector.get('Utils')
        Utils.handleTokenError(data.data)
      data
    responseError:(data)->
      if data && data.data && data.data.message == 'TOKEN_ERROR'
        Utils = $injector.get('Utils')
        Utils.handleTokenError(data.data)
      data
  }
  myInterceptor
)
